load("../src/sim-0.26-debug.js");
load("../src/datacenter.js");
load("../src/Base.js");
load("../src/switch.js");
load("../src/disk.js");
load("../src/namenode.js");
load("../src/datanode.js");
load("../src/client.js");
load("../src/host.js");
load("unittest.js");

if (!console) {
	var console = {};
	if (print) console.log = print;
	else console.log = function () {};
}

var SocketApp = {
	start: function (host) {
		this.host = host;
		this.socket = this.host.socket(this, this.recv, 1024);
	},
	
	recv: function (src, sport, dport, data, size) {
		this.result.push([src, this.time()].join("/"));
	},
	
	do_send: function (destIP, data, size, at) {
		if (!at) at = 0;
		this.setTimer(at).done(function () {
		this.socket.sendto(destIP, 1024, data, size);
		});
	}
};

var conf = {
	racks: [{name: 'r1'}],
	switches: [{name: 'sw', speed:100, ports: 2}],
	disks: [{name: 'disk1'}],
	hosts: [{name: 'client', connect: 'sw', disk: 'disk1', apps:['socketapp']},
	        {name: 'server', connect: 'sw', disk: 'disk1', apps:['socketapp']}]
};

AppRegistry['socketapp'] = SocketApp;

var SocketTest = UnitTest.extend({
	setup: function () {
		this.dc = new DataCenter();
		this.dc.load(conf);
		this.result = [];
		this.dc.getApplication('client', 'socketapp').result = this.result;
		this.dc.getApplication('server', 'socketapp').result = this.result;
	},

	testSocketSimple: function () {
		var server = this.dc.getHost('server');
		var clientapp = this.dc.getApplication('client', 'socketapp');
		clientapp.do_send(server.ip, {}, 1000);
		clientapp.do_send(server.ip, {}, 1000);
		
		this.dc.sim.simulate(100);
		
		this.eqList(this.result, ["2/11", "2/21"]);
	},
	testSocketDuplex: function () {
		var server = this.dc.getHost('server');
		var client = this.dc.getHost('client');
		var capp = this.dc.getApplication('client', 'socketapp');
		var sapp = this.dc.getApplication('server', 'socketapp');
		capp.do_send(server.ip, {}, 1000, 10);
		sapp.do_send(client.ip, {}, 1000, 10);
		
		this.dc.sim.simulate(100);
		
		this.eqList(this.result, ["2/21", "4/21"]);
	}
});

new SocketTest().run();